package com.zhxy.handler;

import com.zhxy.result.R;
import com.zhxy.utils.JSONUtils;
import com.zhxy.utils.ResponseUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        // 登录失败的统一结果
        R result = R.FALL(exception.getMessage());

        // 把封装结果转换成JSON字符串
        String json = JSONUtils.toJSON(result);

        // 把失败信息响应给前端
        ResponseUtils.write(response,json);
    }
}
